package com.zdpx.pxframework.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zdpx.pxframework.redis.service.RedisService;
import com.zdpx.pxframework.system.entity.RoleDepartmentDataScope;
import com.zdpx.pxframework.system.mapper.RoleDepartmentDataScopeMapper;
import com.zdpx.pxframework.system.service.RoleDepartmentDataScopeService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.zdpx.pxframework.core.constant.RedisKeyConstant.ROLE_SELF_DEPT_DATA_PERMISSION_KEY;


/**
 * 角色部门数据权限信息 服务实现类
 *
 * @Description:
 * @Author: Cheng Xiaoxiao
 * @Date: 2022-05-26 16:43:27
 */
@Service
public class RoleDepartmentDataScopeServiceImpl extends ServiceImpl<RoleDepartmentDataScopeMapper, RoleDepartmentDataScope> implements RoleDepartmentDataScopeService {

    @Resource
    RedisService redisService;

    /**
     * 根据角色ID列表查询所拥有的部门ID列表
     *
     * @param roleIds 角色ID
     * @return 部门权限数据
     */
    @Override
    public List<String> listDepartmentsByRoleIds(List<String> roleIds) {
        List<String> departmentList = new ArrayList<>();
        //保存到redis
        for (String roleId : roleIds) {
            String redisKey = ROLE_SELF_DEPT_DATA_PERMISSION_KEY + roleId;
            List<String> roleDepartments = redisService.getCacheObject(redisKey);
            if (roleDepartments == null) {
                List<RoleDepartmentDataScope> dataScopeList = this.list(new LambdaQueryWrapper<RoleDepartmentDataScope>()
                        .select(RoleDepartmentDataScope::getDepartmentId)
                        .eq(RoleDepartmentDataScope::getRoleId, roleId));

                roleDepartments = dataScopeList.stream().map(RoleDepartmentDataScope::getDepartmentId).collect(Collectors.toList());
                //保存到redis中
                redisService.setCacheObject(redisKey, roleDepartments);
            }
            departmentList.addAll(roleDepartments);
        }
        return departmentList;
    }
}
